<template>
  <div class="container">
    <view class="form-container">
      <!-- 第一行: 姓名和性别 -->
      <view class="input-row">
        <view class="input-item">
          <text class="label">姓</text>
          <input v-model="name" class="text-input" placeholder="请输入姓名" />
        </view>
        <view class="input-item">
          <text class="label">性别</text>
          <picker mode="selector" :range="['男', '女']" @change="onGenderChange" :value="genderIndex">
            <view class="picker-value">{{ gender || '选择' }}</view>
          </picker>
        </view>
      </view>

      <!-- 第二行: 父母生肖 -->
      <view class="input-row">
        <view class="input-item">
          <text class="label">父生肖</text>
          <picker mode="selector" :range="zodiacList" @change="onFatherZodiacChange" :value="fatherZodiacIndex">
            <view class="picker-value">{{ fatherZodiac || '选择' }}</view>
          </picker>
        </view>
        <view class="input-item">
          <text class="label">母生肖</text>
          <picker mode="selector" :range="zodiacList" @change="onMotherZodiacChange" :value="motherZodiacIndex">
            <view class="picker-value">{{ motherZodiac || '选择' }}</view>
          </picker>
        </view>
      </view>

      <!-- 第三行: 兄妹信息 -->
      <view class="input-row">
        <view class="input-item">
          <text class="label">兄妹数</text>
          <input v-model="siblingsCount" type="number" class="text-input" placeholder="请输入" />
        </view>
        <view class="input-item">
          <text class="label">排行</text>
          <input v-model="birthOrder" type="number" class="text-input" placeholder="请输入" />
        </view>
      </view>

      <!-- 第四行: 日历类型和职业 -->
      <view class="input-row">
        <view class="input-item">
          <text class="label">日历</text>
          <picker mode="selector" :range="['公历', '农历']" @change="onCalendarTypeChange" :value="calendarIndex">
            <view class="picker-value">{{ calendarType || '选择' }}</view>
          </picker>
        </view>
        <view class="input-item">
          <text class="label">职业</text>
          <picker mode="selector" :range="occupationList" @change="onOccupationChange" :value="occupationIndex">
            <view class="picker-value">{{ occupation || '选择' }}</view>
          </picker>
        </view>
      </view>

      <!-- 第五行: 出生日期 -->
      <view class="input-row">
        <view class="input-item full-width">
          <text class="label">出生日期</text>
          <picker mode="date" @change="onDateChange" :value="birthDate">
            <view class="picker-value">{{ birthDate || '请选择出生日期' }}</view>
          </picker>
        </view>
      </view>

      <!-- 第六行: 出生时间 -->
      <view class="input-row">
        <view class="input-item full-width">
          <text class="label">出生时间</text>
          <picker mode="time" @change="onTimeChange" :value="birthTime">
            <view class="picker-value">{{ birthTime || '请选择出生时间' }}</view>
          </picker>
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="button-container">
        <button class="submit-button" @click="getFateAnalysis" :disabled="isLoading">
          <span v-if="!isLoading">获取命运分析</span>
          <span v-else class="loading-text">
            分析中<span class="dot-animation">...</span>
          </span>
        </button>
      </view>
    </view>

    <!-- 结果展示区域 -->
    <view v-if="renderedOutput" class="output-container">
      <view class="output-title">分析结果</view>
      <view class="output">
        <div v-html="renderedOutput"></div>
      </view>
    </view>
  </div>
</template>

<script>
// 引入 towxml 库
// import Towxml from 'towxml'
import marked from 'marked';
marked.setOptions({
  breaks: true,       // 将换行转换为 <br>
  sanitize: true,     // 清理危险 HTML
  smartypants: true,  // 自动转换引号、破折号等
  silent: true        // 禁止控制台警告
});

export default {
  data() {
    return {
      name: '',
      fatherZodiac: '',
      motherZodiac: '',
      siblingsCount: '',
      birthOrder: '',
      occupation: '',
      fatherZodiacIndex: 0,
      motherZodiacIndex: 0,
      zodiacList: ['鼠', '牛', '虎', '兔', '龙', '蛇', '马', '羊', '猴', '鸡', '狗', '猪'],
      gender: '',        // 性别
      calendarType: '',  // 日历类型（公历/农历）
      birthDate: '',     // 出生日期
      birthTime: '',     // 出生时间
      remark: '',        // 备注
      genderIndex: 0,    // 性别索引
      calendarIndex: 0,  // 日历类型索引
      birthInfo: '',
      outputText: '',
      isLoading: false,
      requestTask: null // 添加请求任务引用
    };
  },
  computed: {
    isFormValid() {
      return (
        this.gender && 
        this.calendarType && 
        this.birthDate && 
        this.birthTime
      );
    },
    renderedOutput() {
      if (!this.outputText || typeof this.outputText !== 'string') return '';
      
      // 尝试检测是否为 Markdown 格式
      const isMarkdown = this.isMarkdownContent(this.outputText);
      
      try {
        if (isMarkdown) {
          // 使用 Towxml 或 marked 处理
          return marked.parse(this.outputText); // 或 Towxml 的逻辑
        } else {
          // 纯文本转为简单 Markdown 再渲染
          const markdownText = `# 命运分析\n\n${this.outputText}`;
          return marked.parse(markdownText);
        }
      } catch (error) {
        // 回退为纯文本显示
        return `<div>${this.outputText.replace(/</g, '&lt;')}</div>`;
      }
    }
  },
  
  methods: {
    onFatherZodiacChange(e) {
      this.fatherZodiac = this.zodiacList[e.detail.value];
      this.fatherZodiacIndex = e.detail.value;
    },
    onMotherZodiacChange(e) {
      this.motherZodiac = this.zodiacList[e.detail.value];
      this.motherZodiacIndex = e.detail.value;
    },
    // 性别选择处理
    onGenderChange(e) {
      this.gender = ['男', '女'][e.detail.value];
      this.genderIndex = e.detail.value;
    },
    
    // 日历类型选择处理
    onCalendarTypeChange(e) {
      this.calendarType = ['公历', '农历'][e.detail.value];
      this.calendarIndex = e.detail.value;
    },
    
    // 日期选择处理
    onDateChange(e) {
      this.birthDate = e.detail.value;
    },
    
    // 时间选择处理
    onTimeChange(e) {
      this.birthTime = e.detail.value;
    },
    async getFateAnalysis() {
      this.birthInfo = `姓名：${this.name}，性别：${this.gender}，父亲生肖：${this.fatherZodiac}，母亲生肖：${this.motherZodiac}，兄妹人数：${this.siblingsCount}，排行：${this.birthOrder}，职业：${this.occupation}，${this.calendarType}${this.birthDate} ${this.birthTime}`;
      if (!this.birthInfo.trim()) {
        uni.showToast({ title: '请输入出生信息', icon: 'none' });
        return;
      }
      console.log('this.loading ...', this.isLoading);
      if (this.isLoading) return;

      this.isLoading = true;
      this.outputText = '';

      try {
        // 创建请求任务
        this.requestTask = wx.request({
          url: 'https://api.sancns.com/v1/xcx/ai/getFateAnalysis',
          method: 'GET',
          responseType: 'text',
          data: {
            user_input: this.birthInfo
          },
          header: {
            'Content-Type': 'application/json',
            'Accept': 'text/event-stream'
          },
          enableChunked: true, // 开启分块传输模式
          success: (res) => {
            if (res.statusCode !== 200) {
              throw new Error(`请求失败: ${res.statusCode}`);
            }
          },
          fail: (err) => {
            throw err;
          },
          complete: () => {
          // 请求结束时处理残留数据
          if (this.buffer.trim()) {
            this.processEvent(this.buffer.trim());
            this.buffer = '';
          }
          this.isLoading = false;
      }
        });

        // 监听分块数据接收
        let buffer = '';
        this.requestTask.onChunkReceived((res) => {
          const chunk = this.decodeChunk(res.data);
          this.buffer += chunk;

          let lastIndex = 0;
          while (true) {
            const eventEndIndex = this.buffer.indexOf('\n\n', lastIndex);
            if (eventEndIndex === -1) break;
            
            const eventData = this.buffer.slice(lastIndex, eventEndIndex).trim();
            lastIndex = eventEndIndex + 2;
            
            if (eventData) {
              this.processEvent(eventData);
            }
          }
          this.buffer = this.buffer.slice(lastIndex);
        });

      } catch (err) {
        console.error('请求失败:', err);
        uni.showToast({ title: '分析失败，请重试', icon: 'none' });
        this.isLoading = false;
      }
    },
    isMarkdownContent(text) {
        // 简单检测是否包含 Markdown 语法
        const markdownPatterns = [
          /^#+ .*$/m,  // 标题
          /\*\*.+?\*\*/,  // 粗体
          /\*.+?\*/,  // 斜体
          /\[.+?\]\(.+?\)/,  // 链接
          /^- .*$/m,  // 无序列表
          /^[0-9]+\. .*$/m,  // 有序列表
          /^>.+$/m,  // 引用
          /`{1,3}[\s\S]*?`{1,3}/  // 代码块
        ];
        
        return markdownPatterns.some(pattern => pattern.test(text));
      },
    // 处理SSE事件
    processEvent(eventData) {
      if (!eventData.startsWith('data:')) return;

      const jsonStr = eventData.slice(5).trim();
      if (!jsonStr) return;

      try {
        const data = JSON.parse(jsonStr);
        this.outputText += data.content || '';
      } catch (e) {
        // 尝试修复常见 JSON 错误（如未闭合括号）
        const repairedJson = jsonStr.replace(/([\{,]\s*)(['"])?([a-zA-Z0-9_]+)(['"])?:/g, '$1"$3":');
        try {
          const data = JSON.parse(repairedJson);
          this.outputText += data.content || '';
        } catch (e) {
          console.error('修复后仍解析失败:', repairedJson);
        }
      }
    },
    // 修改后的decodeChunk方法
    decodeChunk(chunk) {
      if (chunk instanceof ArrayBuffer) {
        // 手动解码 ArrayBuffer 为字符串
        let result = '';
        const uint8Array = new Uint8Array(chunk);
        for (let i = 0; i < uint8Array.length; i++) {
          result += String.fromCharCode(uint8Array[i]);
        }
        return result;
      }
      return chunk;
    },

  },
  beforeUnmount() {
    // 组件卸载时终止请求
    if (this.requestTask) {
      this.requestTask.abort();
    }
  }
};
</script>

<style>
.container {
  padding: 30rpx;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.form-container {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin-bottom: 30rpx;
}

.input-row {
  display: flex;
  margin-bottom: 24rpx;
  justify-content: space-between;
}

.input-item {
  flex: 1;
  margin-right: 20rpx;
}

.input-item:last-child {
  margin-right: 0;
}

.full-width {
  width: 100%;
}

.label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 8rpx;
  display: block;
}

.text-input {
  height: 80rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  background-color: #f9f9f9;
  width: 100%;
  box-sizing: border-box;
}

.picker-value {
  height: 80rpx;
  line-height: 80rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  background-color: #f9f9f9;
  width: 100%;
  box-sizing: border-box;
  color: #333;
}

.button-container {
  margin-top: 40rpx;
  display: flex;
  justify-content: center;
}

.submit-button {
  width: 80%;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #4a90e2;
  color: white;
  font-size: 32rpx;
  font-weight: bold;
  border-radius: 45rpx;
  text-align: center;
  box-shadow: 0 4rpx 12rpx rgba(74, 144, 226, 0.3);
  transition: all 0.3s ease;
  position: relative; /* 添加相对定位 */
}

.submit-button:active {
  transform: scale(0.98);
  box-shadow: 0 2rpx 6rpx rgba(74, 144, 226, 0.3);
}

.submit-button[disabled] {
  background-color: #cccccc;
  box-shadow: none;
}

/* 添加加载动画样式 */
.loading-text {
  display: inline-block;
}

.dot-animation {
  display: inline-block;
  animation: dotAnimation 1.5s infinite;
}

@keyframes dotAnimation {
  0% { opacity: 0.2; }
  20% { opacity: 1; }
  100% { opacity: 0.2; }
}

/* 结果展示区域样式 */
.output-container {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.output-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  text-align: center;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.output {
  font-size: 30rpx;
  color: #444;
  line-height: 1.8;
}

.output p {
  margin: 0px 0;
  line-height: 1.5;
}

.output .strong {
  font-weight: bold;
  color: #222;
}

.output .em {
  font-style: italic;
  color: #555;
}

.output .code {
  padding: 3px 10px;
  background: #f5f5f5;
  border-radius: 6px;
  font-family: monospace;
  font-size: 26rpx;
  color: #e83e8c;
}

.output .li {
  margin-left: -20px;
  padding-left: 0;
  line-height: 1.4;
  display: flex;
  align-items: flex-start;
}

.output .li:before {
  content: "•";
  position: absolute;
  left: -85px;
  top: 0;
}

.output .a {
  color: #4a90e2;
  text-decoration: none;
  border-bottom: 1rpx solid rgba(74, 144, 226, 0.3);
}

.output .blockquote {
  margin: 15px 0;
  padding: 10px 15px;
  border-left: 6rpx solid #4a90e2;
  background: #f8f9fa;
  color: #555;
  font-style: italic;
}

.output .hr {
  margin: 30px 0;
  border: none;
  border-top: 1rpx solid #eee;
}

.output h1, .output h2, .output h3, .output h4 {
  margin: 30px 0 20px;
  color: #333;
  font-weight: bold;
}

.output h1 {
  font-size: 40px;
}

.output h2 {
  font-size: 36px;
}

.output h3 {
  font-size: 32px;
}

.output h4 {
  font-size: 30px;
}

/* 修改列表样式，减少列表项间距 */
.output ul, .output ol {
  margin: 10px 0; /* 减少列表上下间距 */
  padding-left: 30px !important;; /* 统一控制列表缩进 */
}

.output div > ul,
.output div > ol {
  padding-left: 30px;
}
/* 修改列表项样式 */
.output li {
  margin: 8px 0; /* 减少列表项间距 */
  position: relative;
  line-height: 1.6;
}

/* 覆盖marked生成的默认列表样式 */
.output ul li {
  list-style-type: none;
  position: relative;
}

.output ul li::before {
  content: "•";
  position: absolute;
  left: -20px; /* 调整符号位置 */
  color: #4a90e2;
  font-size: 36rpx;
}

.output ol li {
  list-style-type: none;
  counter-increment: item;
  position: relative;
}

.output ol {
  counter-reset: item;
}
.output ol li::before {
  content: counter(item) ".";
  counter-increment: item;
  position: absolute;
  left: -32px; /* 调整数字位置 */
  color: #4a90e2;
  font-weight: bold;
}

/* 如果列表嵌套在段落后面，减少与段落之间的间距 */
.output p + ul, .output p + ol {
  margin-top: 0;
}

.output ul ul,
.output ol ol {
  padding-left: 30rx; /* 减少嵌套缩进 */
  margin: 5rpx 0;
}
/* 处理嵌套列表 */
.output li > ul, .output li > ol {
  margin-top: 0;
  margin-bottom: 0;
  padding-left: 20px;
}
</style>